﻿using System;
using System.Web.UI;
using MS.InformationManagement.Presenter.TRDConfig;
using MS.InformationManagement.Support;
using MS.InformationManagement.Presenter.TRDConfig.Events;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Presenter.Support.Events;
using System.Globalization;
using System.Threading;
using Microsoft.SharePoint;

namespace MS.InformationManagement.WP.RecordCenter.TRDConfig
{
    public partial class TRDConfigUserControl : BaseControl, ITRDConfigView
    {
        private TRDConfigPresenter _Presenter;

        #region [Event Handlers]

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Cache.Remove(string.Format("AvailableDocumentTypes_{0}", SPContext.Current.Web.CurrentUser.LoginName));
                Cache.Remove(string.Format("SelectedDocumentTypes_{0}", SPContext.Current.Web.CurrentUser.LoginName));
                Cache.Remove(string.Format("Series_{0}", SPContext.Current.Web.CurrentUser.LoginName));
                Cache.Remove(string.Format("Backdrop_{0}", SPContext.Current.Web.CurrentUser.LoginName));
                Cache.Remove(string.Format("BackdropChild_{0}", SPContext.Current.Web.CurrentUser.LoginName));
                Cache.Remove(string.Format("Section_{0}", SPContext.Current.Web.CurrentUser.LoginName));
                Cache.Remove(string.Format("Subsection_{0}", SPContext.Current.Web.CurrentUser.LoginName));

                try
                {
                    _Presenter.HandleLoad();
                }
                catch (Exception ex)
                {
                    HandleError(ex);
                }
                CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                TextInfo textInfo = cultureInfo.TextInfo;
                lblDropback.Text = Backdrop == null ? string.Empty : textInfo.ToTitleCase(Backdrop.Title.ToLower());
                lblDropbackChild.Text = BackdropChild == null ? string.Empty : textInfo.ToTitleCase(BackdropChild.Title.ToLower());
                lblSection.Text = Section == null ? string.Empty : textInfo.ToTitleCase(Section.Title.ToLower());
                lblSubsection.Text = Subsection == null ? string.Empty : textInfo.ToTitleCase(Subsection.Title.ToLower());
            }
        }

        protected void TRDConfigUserControl_OnError(object sender, Exception e)
        {
            HandleError(e);
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Page.RegisterAjaxLoaderPlugin();
            this.OnError += new ErrorHandler(TRDConfigUserControl_OnError);
            this.OnSuccess += new SuccessHandler(TRDConfigUserControl_OnSuccess);
            this.OnSerieChanged += new SerieChangeHandler(TRDConfigUserControl_OnSerieChanged);
            this.OnSubserieChanged += new SubserieChangeHandler(TRDConfigUserControl_OnSubserieChanged);

            BackdropChildID = string.IsNullOrEmpty(Request.QueryString.Get("bdcID")) ? 0 : Convert.ToInt32(Request.QueryString.Get("bdcID"));
            BackdropID = string.IsNullOrEmpty(Request.QueryString.Get("bdID")) ? 0 : Convert.ToInt32(Request.QueryString.Get("bdID"));
            SectionID = string.IsNullOrEmpty(Request.QueryString.Get("sID")) ? 0 : Convert.ToInt32(Request.QueryString.Get("sID"));
            SubsectionID = string.IsNullOrEmpty(Request.QueryString.Get("sbID")) ? 0 : Convert.ToInt32(Request.QueryString.Get("sbID"));

            ddlSerie.Required("Debe seleccionar un valor para esta lista", "btn_TRDFormSubmit", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            ddlSubserie.Required("Debe seleccionar un valor para esta lista", "btn_TRDFormSubmit", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);            

            txtbCentralStorage.Numeric("99", false);
            txtbCentralStorage.Required("Este campo es de caracter obligado", "btn_TRDFormSubmit", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);            

            txtbManagementStorage.Numeric("99", false);
            txtbManagementStorage.Required("Este campo es de caracter obligado", "btn_TRDFormSubmit", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            
            txtbNotes.Required("Este campo es de caracter obligado", "btn_TRDFormSubmit", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            if (TRDItemID.HasValue && Operation.Equals("Edit")) { txtbChangeNotes.Required("Este campo es de caracter obligado", "btn_TRDFormSubmit", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight); }

            _Presenter = new TRDConfigPresenter(this);
            btnGuardar.AddLoader();
            ddlSerie.AddLoader();
            ddlSubserie.AddLoader();

            btnFromAvailableToSelectedAll.AddLoader();
            btnFromAvailableToSelectedJustSelected.AddLoader();
            btnFromSelectedToAvailableAll.AddLoader();
            btnFromSelectedToAvailableJustSelected.AddLoader();
            btnUp.AddLoader();
            btnDown.AddLoader();
        }

        void TRDConfigUserControl_OnSubserieChanged(object sender, EventArgs e)
        {
            try
            {
                _Presenter = new TRDConfigPresenter(this);
                _Presenter.SetFormDependantData();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void TRDConfigUserControl_OnSerieChanged(object sender, EventArgs e)
        {
            try
            {
                _Presenter = new TRDConfigPresenter(this);
                _Presenter.LoadSubseries();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void TRDConfigUserControl_OnSuccess(object sender, EventArgs e)
        {
            switch (Operation)
            {
                case "New":
                    HandleSuccess("El registro ha sido almacenado", new WebControl[] { btnCancelar, btnGuardar }, true);
                    break;
                case "Edit":
                    HandleSuccess("El registro ha sido actualizado", new WebControl[] { btnCancelar, btnGuardar }, true);
                    break;
            }
        }

        protected void ddlSerie_SelectedIndexChanged(object sender, EventArgs e)
        {
            OnSerieChanged(sender, e);
        }

        protected void btnGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                _Presenter = new TRDConfigPresenter(this);
                if (SelectedDocumentTypes == null || SelectedDocumentTypes.Count == 0)
                {
                    HandleWarning("Debe seleccionar por lo menos un tipo documental");
                    return;
                }
                if (!TRDItemID.HasValue)
                {
                    if (_Presenter.CanAddTRDConfigItem)
                    {
                        _Presenter.SaveTRDConfigItem();
                        OnSuccess(sender, e);
                    }
                    else
                    {
                        HandleWarning("La combinación de fondo, subfondo, sección, subsección, serie, subserie ya se encuentra en la configuración de la tabla de retención documental.");
                    }
                }
                else {
                    _Presenter.SaveTRDConfigItem();
                    OnSuccess(sender, e);
                }
                
            }
            catch (Exception ex)
            {
                OnError(this, ex);
            }
        }

        protected void ddlSubserie_SelectedIndexChanged(object sender, EventArgs e)
        {
            OnSubserieChanged(sender, e);
        }

        protected void btnFromAvailableToSelectedAll_Click(object sender, EventArgs e)
        {
            try
            {
                _Presenter.SelectAllDocumentTypes();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void btnFromSelectedToAvailableJustSelected_Click(object sender, EventArgs e)
        {
            try
            {
                _Presenter.FromSelectedToAvailable();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void btnFromSelectedToAvailableAll_Click(object sender, EventArgs e)
        {
            try
            {
                _Presenter.UnSelectAllDocumentTypes();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void btnFromAvailableToSelectedJustSelected_Click(object sender, EventArgs e)
        {
            try
            {
                _Presenter.FromAvailableToSelected();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void btnUp_Click(object sender, EventArgs e)
        {
            try
            {
                _Presenter.MoveUp();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void btnDown_Click(object sender, EventArgs e)
        {
            try
            {
                _Presenter.MoveDown();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        #endregion

        #region [ITRDConfigView Members]

        public void Show()
        {
            switch (Operation)
            {
                case "New":
                    rdbDelete.Enabled = true;
                    rdbKeep.Enabled = true;
                    rdbSelect.Enabled = true;
                    rdbTecnicalMean.Enabled = true;
                    txtbCentralStorage.ReadOnly = false;
                    txtbManagementStorage.ReadOnly = false;
                    txtbNotes.ReadOnly = false;
                    txtbCentralStorage.Enabled = true;
                    txtbManagementStorage.Enabled = true;
                    txtbNotes.Enabled = true;
                    divEditMode.Visible = false;
                    lstSelectedDocumentTypes.Enabled = true;
                    lstTipoDocumental.Enabled = true;
                    break;
                case "Edit":
                    ddlSerie.Enabled = false;
                    ddlSubserie.Enabled = false;
                    rdbDelete.Enabled = true;
                    rdbKeep.Enabled = true;
                    rdbSelect.Enabled = true;
                    rdbTecnicalMean.Enabled = true;
                    txtbCentralStorage.ReadOnly = false;
                    txtbManagementStorage.ReadOnly = false;
                    txtbNotes.ReadOnly = false;
                    txtbCentralStorage.Enabled = true;
                    txtbManagementStorage.Enabled = true;
                    txtbNotes.Enabled = true;
                    divEditMode.Visible = true;
                    h3EditMode.Visible = true;
                    lstSelectedDocumentTypes.Enabled = true;
                    lstTipoDocumental.Enabled = true;
                    break;
                case "View":
                    ddlSerie.Enabled = false;
                    ddlSubserie.Enabled = false;
                    rdbDelete.Enabled = false;
                    rdbKeep.Enabled = false;
                    rdbSelect.Enabled = false;
                    rdbTecnicalMean.Enabled = false;
                    txtbCentralStorage.ReadOnly = true;
                    txtbManagementStorage.ReadOnly = true;
                    txtbNotes.ReadOnly = true;
                    txtbCentralStorage.Enabled = false;
                    txtbManagementStorage.Enabled = false;
                    txtbNotes.Enabled = false;
                    divEditMode.Visible = false;
                    btnGuardar.Enabled = false;
                    lstSelectedDocumentTypes.Enabled = false;
                    lstTipoDocumental.Enabled = false;
                    btnCancelar.Text = "Cerrar";

                    break;

            }
        }

        public int? TRDItemID
        {
            get
            {
                return string.IsNullOrEmpty(Request.QueryString.Get("ID")) ? new Nullable<int>() : Convert.ToInt32(Request.QueryString.Get("ID"));
            }
        }

        public string ChangeNotes
        {
            get
            {
                return txtbChangeNotes.Text;
            }
            set
            {
                txtbChangeNotes.Text = value;
            }
        }

        public string Operation
        {
            get
            {
                return string.IsNullOrEmpty(Request.QueryString.Get("strategy")) ? "New" : Request.QueryString.Get("strategy");
            }
        }

        public string BackdropCode
        {
            get
            {
                return lblDropbackCode.Text;
            }
            set
            {
                lblDropbackCode.Text = value;
            }
        }

        public string ChildBackdropCode
        {
            get
            {
                return lblDropbackChildCode.Text;
            }
            set
            {
                lblDropbackChildCode.Text = value;
            }
        }

        public string SectionCode
        {
            get
            {
                return lblSectionCode.Text;
            }
            set
            {
                lblSectionCode.Text = value;
            }
        }

        public string SubsectionCode
        {
            get
            {
                return lblSubsectionCode.Text;
            }
            set
            {
                lblSubsectionCode.Text = value;
            }
        }

        public string SerieCode
        {
            get
            {
                return lblSerieCode.Text;
            }
            set
            {
                lblSerieCode.Text = value;
            }
        }

        public string SubserieCode
        {
            get
            {
                return lblSubSerieCode.Text;
            }
            set
            {
                lblSubSerieCode.Text = value;
            }
        }

        public DAL.RecordCenter.FondosFondo Backdrop
        {
            get { return Cache[string.Format("Backdrop_{0}", SPContext.Current.Web.CurrentUser.LoginName)] as DAL.RecordCenter.FondosFondo; }
            set { Cache[string.Format("Backdrop_{0}", SPContext.Current.Web.CurrentUser.LoginName)] = value; }
        }

        public DAL.RecordCenter.FondosFondo BackdropChild
        {
            get { return Cache[string.Format("BackdropChild_{0}", SPContext.Current.Web.CurrentUser.LoginName)] as DAL.RecordCenter.FondosFondo; }
            set { Cache[string.Format("BackdropChild_{0}", SPContext.Current.Web.CurrentUser.LoginName)] = value; ; }
        }

        public DAL.RecordCenter.SeccionesSeccion Section
        {
            get { return Cache[string.Format("Section_{0}", SPContext.Current.Web.CurrentUser.LoginName)] as DAL.RecordCenter.SeccionesSeccion; }
            set { Cache[string.Format("Section_{0}", SPContext.Current.Web.CurrentUser.LoginName)] = value; }
        }

        public DAL.RecordCenter.SeccionesSeccion Subsection
        {
            get { return Cache[string.Format("Subsection_{0}", SPContext.Current.Web.CurrentUser.LoginName)] as DAL.RecordCenter.SeccionesSeccion; }
            set { Cache[string.Format("Subsection_{0}", SPContext.Current.Web.CurrentUser.LoginName)] = value; }
        }

        public DAL.RecordCenter.Serie Serie
        {
            get
            {
                int serieID = Convert.ToInt32(ddlSerie.SelectedValue);
                return Series.SingleOrDefault(serie => serie.Id.Equals(serieID));
            }
            set
            {
                ddlSerie.SelectedValue = value.Id.ToString();
            }
        }

        public DAL.RecordCenter.Subserie Subserie
        {
            get
            {
                int subserieID = Convert.ToInt32(ddlSubserie.SelectedValue);
                return Subseries.SingleOrDefault(subserie => subserie.Id.Equals(subserieID));
            }
            set
            {
                ddlSubserie.SelectedValue = value.Id.ToString();
            }
        }

        public System.Collections.Generic.List<DAL.RecordCenter.TipoDocumental> AvailableDocumentTypes
        {
            get
            {
                return Cache[string.Format("AvailableDocumentTypes_{0}", SPContext.Current.Web.CurrentUser.LoginName)] as System.Collections.Generic.List<MS.InformationManagement.DAL.RecordCenter.TipoDocumental>;
            }
            set
            {
                Cache[string.Format("AvailableDocumentTypes_{0}", SPContext.Current.Web.CurrentUser.LoginName)] = value;
                lstTipoDocumental.DataSource = value;
                lstTipoDocumental.DataBind();
            }
        }

        public System.Collections.Generic.List<DAL.RecordCenter.TipoDocumental> AvailableSelectedDocumentTypes
        {
            get
            {
                return (from documentType in AvailableDocumentTypes
                        join
                            ListItem item in lstTipoDocumental.Items
                            on documentType.Id.ToString() equals (item.Value)
                        where item.Selected.Equals(true)
                        select documentType).ToList();
            }
        }

        public System.Collections.Generic.List<DAL.RecordCenter.TipoDocumental> SelectedDocumentTypes
        {
            get
            {
                return Cache[string.Format("SelectedDocumentTypes_{0}", SPContext.Current.Web.CurrentUser.LoginName)] as System.Collections.Generic.List<DAL.RecordCenter.TipoDocumental>;
            }
            set
            {
                Cache[string.Format("SelectedDocumentTypes_{0}", SPContext.Current.Web.CurrentUser.LoginName)] = value;
                lstSelectedDocumentTypes.DataSource = value;
                lstSelectedDocumentTypes.DataBind();
            }
        }

        public System.Collections.Generic.List<DAL.RecordCenter.TipoDocumental> SelectedSelectedDocumentTypes
        {
            get
            {
                return (from documentType in SelectedDocumentTypes
                        join
                            ListItem item in lstSelectedDocumentTypes.Items
                            on documentType.Id.ToString() equals (item.Value)
                        where item.Selected.Equals(true)
                        select documentType).ToList();
            }
        }

        public System.Collections.Generic.List<DAL.RecordCenter.Serie> Series
        {
            get
            {
                return Cache[string.Format("Series_{0}", SPContext.Current.Web.CurrentUser.LoginName)] as System.Collections.Generic.List<MS.InformationManagement.DAL.RecordCenter.Serie>;
            }
            set
            {
                Cache[string.Format("Series_{0}", SPContext.Current.Web.CurrentUser.LoginName)] = value;
                ddlSerie.Items.Clear();

                ddlSerie.Items.Add(new ListItem("----Seleccione----", "0"));
                ddlSerie.DataSource = value;
                ddlSerie.DataBind();
            }
        }

        public System.Collections.Generic.List<DAL.RecordCenter.Subserie> Subseries
        {
            get
            {
                return Cache["Subseries"] as System.Collections.Generic.List<MS.InformationManagement.DAL.RecordCenter.Subserie>;
            }
            set
            {
                Cache["Subseries"] = value.ToList();
                ddlSubserie.Items.Clear();
                ddlSubserie.Items.Add(new ListItem("----Seleccione----", "0"));
                ddlSubserie.DataSource = Cache["Subseries"];
                ddlSubserie.DataBind();
            }
        }

        public bool Keep
        {
            get
            {
                return rdbKeep.Checked;
            }
            set
            {
                rdbKeep.Checked = value;
            }
        }

        public bool TechnicalMean
        {
            get
            {
                return rdbTecnicalMean.Checked;
            }
            set
            {
                rdbTecnicalMean.Checked = value;
            }
        }

        public bool Delete
        {
            get
            {
                return rdbDelete.Checked;
            }
            set
            {
                rdbDelete.Checked = value;
            }
        }

        public bool Select
        {
            get
            {
                return rdbSelect.Checked;
            }
            set
            {
                rdbSelect.Checked = value;
            }
        }

        public double CentralStorageTime
        {
            get
            {
                return Convert.ToDouble(txtbCentralStorage.Text);
            }
            set
            {
                txtbCentralStorage.Text = value.ToString();
            }
        }

        public double GeneralManagementStorageTime
        {
            get
            {
                return Convert.ToDouble(txtbManagementStorage.Text);
            }
            set
            {
                txtbManagementStorage.Text = value.ToString();
            }
        }

        public int BackdropID
        {
            get;
            set;
        }

        public int BackdropChildID
        {
            get;
            set;
        }

        public int SectionID
        {
            get;
            set;
        }

        public int SubsectionID
        {
            get;
            set;
        }

        public string Notes
        {
            get
            {
                return txtbNotes.Text;
            }
            set
            {
                txtbNotes.Text = value;
            }
        }

        public event SerieChangeHandler OnSerieChanged;
        public event SubserieChangeHandler OnSubserieChanged;

        #endregion

        public event ErrorHandler OnError;
        public event SuccessHandler OnSuccess;

    }
}
